package com.qcby.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qcby.common.ExamDetail.AiCorrectionResult;
import com.qcby.common.ExamDetail.ExamSubmitRequest;
import com.qcby.common.ExamDetail.SaveScore;
import com.qcby.dao.ExamDetailDao;
import com.qcby.entity.*;
import com.qcby.service.ExamDetailService;
import com.qcby.util.DeepSeekUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
public class ExamDetailServiceImpl implements ExamDetailService {


    @Autowired
    ExamDetailDao examDetailDao;

    @Autowired
    DeepSeekUtils deepSeekUtils;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public Result<Exam> loadExamInfo(int id) {
        return Result.success(examDetailDao.loadExamInfo(id));
    }

    @Override
    public Result<List<QuestionBank>> loadMultipleChoiceQuestions(int e_id) {
        return Result.success(examDetailDao.loadMultipleChoiceQuestions(e_id));
    }

    @Override
    public Result<List<QuestionBank>> loadFillInTheBlankQuestions(int e_id) {
        return Result.success(examDetailDao.loadFillInTheBlankQuestions(e_id));
    }

    @Override
    public Result<List<QuestionBank>> loadingTrueOrFalseQuestions(int e_id) {
        return Result.success(examDetailDao.loadingTrueOrFalseQuestions(e_id));
    }

    @Override
    public Result<List<QuestionBank>> loadShortAnswerQuestions(int e_id) {
        return Result.success(examDetailDao.loadShortAnswerQuestions(e_id));
    }

    @Override
    public Result<List<QuestionBank>> loadingCalculationQuestions(int e_id) {
        return Result.success(examDetailDao.loadingCalculationQuestions(e_id));
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result<Integer> submitToAI(ExamSubmitRequest request) {
        try {
            // 1. 验证请求参数
            if (request == null || request.getQuestions() == null || request.getQuestions().isEmpty()) {
                return Result.error("提交的试卷数据为空");
            }

            // 获取学生姓名
            String studentName = request.getStudent();
            // 通过学生姓名获取id
            Student student = examDetailDao.getStudentInfoByName(studentName);
            int s_id = student.getId();

            // 2. 构建提示话术
            String prompt = "请你作为考试阅卷老师，对我提交的考试进行批改。请按照以下要求处理：\n" +
                    "1. 首先计算并给出总分(选择题2分，判断题2分，填空题5分，简答题10分，计算题10分)\n" +
                    "2. 识别出所有错题，对每道错题需要包含：\n" +
                    "   - 题目ID（question_id）\n" +
                    "   - 题目内容（question）\n" +
                    "   - 学生答案（user_answer）\n" +
                    "   - 参考答案（correct_answer）\n" +
                    "   - 错误原因分析（error_reason）\n" +
                    "3. 请严格按照以下JSON格式返回结果，不要添加任何额外解释文字：\n" +
                    "{\n" +
                    "  \"total_score\": 85,  // 总分\n" +
                    "  \"wrong_questions\": [  // 错题列表\n" +
                    "    {\n" +
                    "      \"question_id\": \"q3\",\n" +
                    "      \"question\": \"以下哪个不是Java基本数据类型？\",\n" +
                    "      \"userAnswer\": \"A.String\",\n" +
                    "      \"correctAnswer\": \"A.String\",\n" +
                    "      \"errorReason\": \"String是引用类型，不是基本数据类型\"\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}\n\n" +
                    "以下是学生的答题内容：\n" +
                    deepSeekUtils.convertQuestionsToText(request.getQuestions());

            // 3. 调用AI接口获取批改结果
            String aiResponse = deepSeekUtils.askAi(prompt);
            if (aiResponse == null || aiResponse.trim().isEmpty()) {
                return Result.error("AI批改失败，未返回有效结果");
            }

            // 4. 解析AI返回的JSON为自定义实体类（先定义AiResult类，包含total_score和wrong_questions）
            AiCorrectionResult aiResult = objectMapper.readValue(aiResponse, AiCorrectionResult.class);
            Integer totalScore = aiResult.getTotal_score();
            List<ErrorCollection> wrongQuestions = aiResult.getWrong_questions();

            // 5. 处理总分
            System.out.println("本次考试总分：" + totalScore);
            int examId = Integer.parseInt(request.getExam_id());

            SaveScore info = new SaveScore();

            info.setEid(examId);
            info.setSid(s_id);
            info.setScore(String.valueOf(totalScore));
            info.setStatus("已存档");
            System.out.println("info = " + info);

            int count = examDetailDao.updateExamScore(info);
            if(count == 1){
                System.out.println("总分已存入数据库");
            }

            // 6. 处理错题，存入错题表（假设已注入errorCollectionDao）
            for (ErrorCollection error : wrongQuestions) {
                // 若ErrorCollection有自增id，无需手动设置；若有其他关联字段（如用户id、考试id），需在此赋值
                // error.setUserId(当前用户id);
                // error.setExamId(当前考试id);
                error.setStudent(request.getStudent());
                System.out.println("准备存入错题：" + error);
                examDetailDao.insertToErrorCollection(error);
            }

            // 7. 返回处理结果（可根据需求返回解析后的对象或原始JSON，这里返回解析后的结果示例）
            return Result.success(totalScore);

        } catch (IOException e) {
            // 处理网络请求异常、JSON解析异常等
            return Result.error("调用AI接口失败或解析结果异常: " + e.getMessage());
        } catch (Exception e) {
            // 处理其他未知异常
            return Result.error("批改过程发生错误: " + e.getMessage());
        }
    }


}
